#include <iostream>
#include <execinfo.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <memory>

// 解析符号信息
std::string demangle(const char* symbol) {
    int status = -1;
    std::unique_ptr<char, void(*)(void*)> res{
        abi::__cxa_demangle(symbol, NULL, NULL, &status),
        std::free
    };
    return (status == 0) ? res.get() : symbol;
}

// 打印函数调用栈
void printStackTrace() {
    void* array[10];
    size_t size;

    // 获取调用栈信息
    size = backtrace(array, 10);

    // 将调用栈信息转换为符号信息
    char** strings = backtrace_symbols(array, size);

    if (strings) {
        std::cout << "Stack trace:\n";
        for (size_t i = 0; i < size; ++i) {
            // 解析每个符号信息
            Dl_info info;
            if (dladdr(array[i], &info) && info.dli_sname) {
                std::string demangled_name = demangle(info.dli_sname);
                std::cout << "#" << i << " " << info.dli_fname << " : " << demangled_name << " + " << (void*)((char*)array[i] - (char*)info.dli_saddr) << "\n";
            } else {
                std::cout << strings[i] << "\n";
            }
        }
        free(strings);
    }
}

// 一个递归函数，用于触发栈跟踪
void recursiveFunction(int depth) {
    if (depth > 0) {
        recursiveFunction(depth - 1);
    } else {
        printStackTrace();
    }
}

int main() {
    // 触发栈跟踪
    recursiveFunction(5);

    return 0;
}